package com.light.gulimall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.light.common.utils.PageUtils;
import com.light.common.utils.Query;
import com.light.gulimall.order.dao.OrderItemDao;
import com.light.gulimall.order.entity.OrderItemEntity;
import com.light.gulimall.order.service.OrderItemService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;


@Service("orderItemService")
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderItemEntity> page = this.page(
                new Query<OrderItemEntity>().getPage(params),
                new QueryWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 同一个消息只能被一个监听者接受
     * 一个消息处理完成后，才能处理下一个消息
     * @param message
     * @param channel
     */
    @RabbitListener(queues = "hello-java-queue")
    public void listenMessage(Message message, Channel channel) {
        System.out.println("listenMessage接收到的消息" + message);
        System.out.println("");
//        throw new NullPointerException();
    }
//        long deliveryTag = message.getMessageProperties().getDeliveryTag();
//        try {
//            //手动确认
//            if (deliveryTag % 2 == 0) {
//                //签收
//                channel.basicAck(deliveryTag, false);
//                System.out.println("listenMessage接收到的消息" + message);
//            } else {
//                //拒绝
//                channel.basicNack(deliveryTag, false, true);
//                System.out.println("listenMessage拒绝了消息" + message);
//            }
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }


    @RabbitListener(queues = {"hello-java-queue","hello-java-fanout-queue"})
    public void receiveQueue(Message message,Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            channel.basicAck(deliveryTag, false);
            System.out.println("receiveQueue接收到的消息"+message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 监听通配符队列1 和交换机绑定的路由键是 #.java
     * @param message
     */
    @RabbitListener(queues = "hello-java-topic-queue2")
    public void receiveTopicQueue(String message) {
        System.out.println("监听hello-java-topic-queue2的消息是" + message);
    }

}